import json
import random
from datetime import datetime
import os
import time

# 配置文件路径
DATA_FILE = "src/前端/data.json"

def generate_mock_data():
    """生成模拟的电力设备数据"""
    devices = ["BOILER_1", "TURBINE_1", "COOLING_1", "PUMP_1", "GENERATOR_1"]
    points = []
    
    for device in devices:
        # 基础数据
        base_data = {
            "device_id": device,
            "timestamp": datetime.now().isoformat(),
            "temperature": random.uniform(50, 400) if "BOILER" in device else random.uniform(20, 100),
            "pressure": random.uniform(1.0, 15.0),
            "vibration": random.uniform(0.01, 0.5),
            "status": "NORMAL"
        }
        
        # 10%概率生成异常数据
        if random.random() < 0.1:
            base_data["status"] = "ALARM"
            if "BOILER" in device:
                base_data["temperature"] = random.uniform(401, 450)
            base_data["pressure"] = random.uniform(16.0, 20.0)
            base_data["vibration"] = random.uniform(0.6, 1.0)
        
        points.append(base_data)
    
    return {
        "timestamp": datetime.now().isoformat(),
        "point_count": len(points),
        "points": points
    }

def update_data_file():
    """更新数据文件"""
    try:
        # 如果文件不存在，创建初始数据
        if not os.path.exists(DATA_FILE):
            initial_data = []
            with open(DATA_FILE, 'w') as f:
                json.dump(initial_data, f)
        
        # 读取现有数据
        with open(DATA_FILE, 'r') as f:
            existing_data = json.load(f)
        
        # 生成新数据并追加
        new_entry = generate_mock_data()
        existing_data.append(new_entry)
        
        # 保持最多100条记录
        if len(existing_data) > 100:
            existing_data = existing_data[-100:]
        
        # 写入文件
        with open(DATA_FILE, 'w') as f:
            json.dump(existing_data, f, indent=2)
        
        print(f"数据已更新，当前记录数: {len(existing_data)}")
        
    except Exception as e:
        print(f"处理数据文件时出错: {e}")

if __name__ == "__main__":
    print("电力设备数据生成器启动...")
    print(f"数据将保存到: {os.path.abspath(DATA_FILE)}")
    
    try:
        while True:
            update_data_file()
            time.sleep(2)  # 每2秒更新一次数据
    except KeyboardInterrupt:
        print("\n数据生成器已停止")